package com.wk.repeaters;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 按固定时间间隔执行任务，类似于{@link java.util.Timer}<br>
 * 固定时间间隔：从一次任务结束到下一次任务开始，二者相差的时间固定
 * 
 * @author Bai Yu
 *
 */
public class FixedIntervalRepeater implements Repeater {
	/**
	 * 按固定时间间隔执行任务<br>
	 * 
	 * @param interval
	 *            时间间隔（单位：毫秒）
	 */
	public FixedIntervalRepeater(long interval) {
		timer = new Timer();
		this.interval = interval;
	}

	@Override
	public void schedule(Runnable task) {
		this.task = task;
	}

	@Override
	public void start() {
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				task.run();
			}
		}, 0, interval);
	}

	@Override
	public void cancel() {
		timer.cancel();
	}

	private Runnable task;
	private long interval;

	private Timer timer;
}
